package com.muyu.danmo.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muyu.danmo.domain.es.PersonInfoEs;
import com.muyu.danmo.esMapper.PersonInfoEsRepository;
import com.muyu.danmo.mapper.DanmoPersonInfoMapper;
import com.muyu.danmo.service.impl.AggregationService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchScrollHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test")
@Slf4j
public class Test {
    @Autowired
    private PersonInfoEsRepository esRepo;

    @Autowired
    private DanmoPersonInfoMapper danmoPersonInfoMapper;

    @Autowired
    private ElasticsearchOperations esOps;


    @Autowired
    private AggregationService aggregationService;


    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;




//    @GetMapping("/find")
//    public void find() throws IOException {
//        aggregationService.performAggregationQuery();
//    }







    @GetMapping("/add")
    public void test(){
        log.info("增加缓存数据！！！！");
        // 3. 全量初始化：分页加载视图并写入 ES
        int batchSize = 500;
        int offset = 1;
        Page<PersonInfoEs> pageList = null;
        String lastId = "1";
        do {
            Page<PersonInfoEs> page = new Page<>(offset, batchSize);
            pageList = danmoPersonInfoMapper.findAll(page, Long.valueOf(lastId));
            if (!pageList.getRecords().isEmpty()) {
                pageList.getRecords().forEach(a ->{
                    String name = StrUtil.cleanBlank(a.getName());
                    if(StrUtil.isNotEmpty(name)){
                        String firstLetter = String.valueOf(PinyinUtil.getFirstLetter(name.charAt(0))).toLowerCase();
                        a.setFirstLetter(firstLetter);
                    }
                    String entry = a.getAddressEntry();
                    if(StrUtil.isNotEmpty(entry)){
                        String entryFirstLetter = String.valueOf(PinyinUtil.getFirstLetter(entry.charAt(0))).toLowerCase();
                        a.setEntryFirstLetter(entryFirstLetter);
                    }
                });
                esRepo.saveAll(pageList.getRecords());
                lastId = pageList.getRecords().get(pageList.getRecords().size() -1).getId();
            }
        } while (!pageList.getRecords().isEmpty());
        log.info("数据填充到es完成！！");
        log.info("增加缓存数据完成！！！！");
    }

    @GetMapping("/update")
    public void update(){

        Query query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchAllQuery())
                .withPageable(PageRequest.of(0, 200)) // 每批 200 条
                .build();

        IndexCoordinates index = IndexCoordinates.of("v_danmo_person_info_all");

        SearchScrollHits<PersonInfoEs> scrollHits =
                elasticsearchRestTemplate.searchScrollStart(800, query, PersonInfoEs.class, index);

        int totalUpdated = 0;
        String scrollId = null;

        try {
            while (scrollHits.hasSearchHits()) {
                scrollId = scrollHits.getScrollId();

                List<PersonInfoEs> updatedList = scrollHits.getSearchHits().stream()
                        .map(SearchHit::getContent)
                        .filter(p -> StrUtil.isNotEmpty(p.getAddressEntry()))
                        .peek(p -> {
//                            String name = StrUtil.cleanBlank(p.getName());
//                            if(StrUtil.isNotEmpty(name)){
//                                String firstLetter = String.valueOf(PinyinUtil.getFirstLetter(name.charAt(0))).toLowerCase();
//                                p.setFirstLetter(firstLetter);
//                            }
                            String entry = StrUtil.cleanBlank(p.getAddressEntry());
                            if(StrUtil.isNotEmpty(entry)){
                                String entryFirstLetter = String.valueOf(PinyinUtil.getFirstLetter(entry.charAt(0))).toLowerCase();
                                p.setEntryFirstLetter(entryFirstLetter);
                            }
                        })
                        .collect(Collectors.toList());

                if (!updatedList.isEmpty()) {
                    esRepo.saveAll(updatedList);
                    totalUpdated += updatedList.size();
                    log.info("✅ 本批次更新了 {} 条", updatedList.size());
                }

                scrollHits = elasticsearchRestTemplate.searchScrollContinue(scrollId, 800, PersonInfoEs.class, index);
            }

            log.info("🎉 所有数据更新完成，共更新了 {} 条", totalUpdated);

        } catch (Exception e) {
            log.error("❌ 更新过程异常：", e);
        } finally {
            if (scrollId != null) {
                elasticsearchRestTemplate.searchScrollClear(Collections.singletonList(scrollId));
                log.info("🧹 已清除 Scroll 上下文");
            }
        }
    }


}


